package com.iseastar.guojiang;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.shouhuobao.station.R;
import com.umeng.analytics.MobclickAgent;

import java.util.Collection;
import java.util.List;

import droid.frame.App;
import droid.frame.activity.base.FrameBaseActivity;
import droid.frame.fragment.FragmentMgr;
import droid.frame.ui.dialog.AppLoading;
import droid.frame.utils.android.Alert;
import droid.frame.utils.android.ImmUtils;
import droid.frame.utils.android.Log;
import droid.frame.utils.android.SharedPref;
import droid.frame.utils.lang.JsonParser;

public abstract class BaseActivity extends FrameBaseActivity {

    private ProgressBar mProgressBar;
    private TextView mEmptyView;

    protected SwipeRefreshLayout mSwipeLayout;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setStatusBarColor(R.color.black_25);
        super.onCreate(savedInstanceState);
    }

    protected void onCreateSuper(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Thread.setDefaultUncaughtExceptionHandler(getApp().getUncaughtExceptionHandler());
        MobclickAgent.onResume(this);
    }

    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelLoadingDialog();
        FragmentMgr.getInstance(this).onDestroy(this);
    }

    @Override
    protected void findViewById() {
        super.findViewById();
        int loadingId = getResources().getIdentifier("loading_progressBar", "id", getPackageName());
        if (loadingId != 0) {
            mProgressBar = (ProgressBar) findViewById(loadingId);
            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.GONE);
            }
        }
        int emptyId = getResources().getIdentifier("empty_text", "id", getPackageName());
        mEmptyView = (TextView) findViewById(emptyId);
        if (mEmptyView != null) {
            ((ViewGroup) mEmptyView.getParent()).setVisibility(View.GONE);
        }
        //
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    }

    protected void onRefreshComplete() {
        if (mSwipeLayout != null) {
            getContext().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mSwipeLayout.setRefreshing(false);
                }
            });
        }
    }

    // 隐藏键盘输入法
    public final static int MSG_IMM_HIDE = 1000;
    public final static int MSG_IMM_SHOW = 1000 + 1;

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_IMM_HIDE:
                ImmUtils.hide(getContext());
        }
        return false;
    }

    public BeeApplication getApp() {
        return (BeeApplication) super.getApplication();
    }

    // ******************************************************************************************

    public boolean isEmpty(Object obj) {
        if (obj instanceof Collection<?>) {
            if (((Collection<?>) obj).isEmpty()) {
                return true;
            }
        }
        if (obj == null || obj.toString().trim().length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }

    /**
     * 不比较 null对象
     *
     * @param obj1
     * @param obj2
     * @return
     */
    public boolean isEquals(Object obj1, Object obj2) {
        if (obj1 == null && obj2 == null) {
            return false;
        }
        if (obj1 != null && obj1.equals(obj2)) {
            return true;
        } else {
            return false;
        }
    }

    public void showLoadingBar() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }

    public void cancelLoadingBar() {
        if (mProgressBar != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        }
    }

    /**
     * 该方法主要考虑到一个界面里多个EmptyView
     *
     * @param emptyText
     */
    protected void setEmptyTextView(TextView emptyText) {
        this.mEmptyView = emptyText;
    }

    public void setEmptyView(ViewGroup viewGroup, String emptyText) {
        if (mEmptyView == null) {
            return;
        }
        //
        if (viewGroup instanceof ListView || viewGroup instanceof GridView) {
            AbsListView mAbsListView = (AbsListView) viewGroup;
            if (mAbsListView == null || mAbsListView.getAdapter() == null || mAbsListView.getAdapter().getCount() == 0) {
                ((View) mEmptyView.getParent()).setVisibility(View.VISIBLE);
                if (isEmpty(emptyText) == false) {
                    mEmptyView.setText(emptyText);
                }
            } else {
                ((View) mEmptyView.getParent()).setVisibility(View.GONE);
            }
        }
    }

    public void showErrorToast(String jsonStr, String attr) {
        Object err = JsonParser.get(jsonStr, attr);
        if (err == null || "".equals(err)) {
            Alert.toast("操作失败");
        } else {
            Alert.toast(err.toString());
        }
    }

    private AppLoading loading;

    public void showLoadingDialog(final String dialogMessage) {
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loading != null && loading.isShowing()) {
                    loading.setMessage(dialogMessage);
                    return;
                } else {
                    loading = new AppLoading(getContext());
                    loading.setMessage(dialogMessage);
                    loading.show();
                }
            }
        });
    }

    protected void cancelLoadingDialog() {
        getContext().runOnUiThread(new Runnable() {
            public void run() {
                if (loading != null) {
                    loading.dismiss();
                }
            }
        });
    }

    public void showToast(final String message) {
        // Alert.toast(message);
        App.getHandler().post(new Runnable() {
            @Override
            public void run() {
                final Toast toast = Toast.makeText(getContext(), message, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        });
    }

    public void startActivity(Class<?> classActivity) {
        Intent intent = new Intent();
        intent.setClass(getContext(), classActivity);
        startActivity(intent);
    }

    public void setSharedPref(String key, String value) {
        SharedPref.put(key, value);
    }

    protected String getSharedPref(String key) {
        return SharedPref.get(key);
    }
    @SuppressLint("RestrictedApi")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        FragmentManager fm = getSupportFragmentManager();
        int index = requestCode >> 16;
        if (index != 0) {
            index--;
            if (fm.getFragments() == null || index < 0
                    || index >= fm.getFragments().size()) {
                Log.d("BaseActivity2", "Activity result fragment index out of range: 0x" + Integer.toHexString(requestCode));
                return;
            }
            Fragment frag = fm.getFragments().get(index);
            if (frag == null) {
                Log.d("BaseActivity2", "Activity result no fragment exists for index: 0x"
                        + Integer.toHexString(requestCode));
            } else {
                handleResult(frag, requestCode, resultCode, data);
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 递归调用，对所有子Fragement生效
     *
     * @param frag
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void handleResult(Fragment frag, int requestCode, int resultCode,
                              Intent data) {
        frag.onActivityResult(requestCode & 0xffff, resultCode, data);
        @SuppressLint("RestrictedApi")
        List<Fragment> frags = frag.getChildFragmentManager().getFragments();
        if (frags != null) {
            for (Fragment f : frags) {
                if (f != null)
                    handleResult(f, requestCode, resultCode, data);
            }
        }
    }
    /**
     * 修改密码的登录按钮
     *
     * @param button
     * @param enable
     */
    public void setButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.change_btn_selector);
            button.setTextColor(getResources().getColorStateList(R.color.white));
        } else {
            button.setBackgroundResource(R.drawable.app_btn_disable);
            button.setTextColor(getResources().getColor(R.color.white));

        }
        button.setPadding(left, top, right, bottom);
    }
}
